<template>
  <div class="main">
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :on-change="handleChange"
      action=""
      :auto-upload="false"
      ref="uploadRef"
    >
      <img v-if="imgUrl" :src="imgUrl" class="avatar" alt="" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-button type="primary" @click="selectFile"
      >选取文件</el-button
    >
    <el-button type="primary" @click="submitUpload" :disabled="uploadDisabled" ref="submitUploadRef"
      >上传到服务器</el-button
    >
  </div>
</template>

<script setup lang="ts">
import type { UploadFile, UploadFiles } from 'element-plus'

import { onMounted, ref } from 'vue'
import { getUserInfo, updateAvatar } from '@/api/user.ts'
const imgUrl = ref<string>('')
const uploadDisabled = ref<boolean>(true)
const submitUploadRef = ref()
const handleChange = (file: UploadFile, fileList: UploadFiles) => {
  const raw = file.raw
  if (!raw) return
  const reader = new FileReader()
  reader.onload = () => (imgUrl.value = reader.result as string)
  reader.readAsDataURL(raw)
  uploadDisabled.value = false
}
const submitUpload = () => {
  updateAvatar(imgUrl.value!)
}
onMounted(async () => {
  const userInfo = await getUserInfo()
  if (userInfo) {
    imgUrl.value = userInfo.user_pic!
  }
})

const uploadRef = ref<UploadInstance>()

const selectFile = () => {
  const input = uploadRef.value!.$el.querySelector('input[type=file]') as HTMLInputElement
  input?.click()
}
</script>

<style scoped>
.main {
  width: 400px;
  height: 400px;
}
</style>
